#include "widget.h"
#include "ui_widget.h"
#include <QTcpSocket>
#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("客户端");
    socket = new QTcpSocket(this);
    socket->connectToHost("127.0.0.1", 9090);//注意，这是非阻塞的
    connect(socket, &QTcpSocket::readyRead, this, [=](){
        QString response = socket->readAll();
        ui->listWidget->addItem("服务器说: " + response);
    });
    bool ret = socket->waitForConnected();//阻塞 --- 三次握手完成之后
    if(!ret)
    {
        QMessageBox::critical(this, "连接服务器出错", socket->errorString());
        exit(1);
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_clicked()
{
    const QString& text = ui->lineEdit->text();
    socket->write(text.toUtf8());
    ui->listWidget->addItem("客户端说: " + text);
    ui->lineEdit->setText("");
}

